import logger from '../utils/logger.js'
/**
 * GOC Trace收集器
 * 用于记录GOC代码执行过程中的所有绘图动作和状态变化
 */
class TraceCollector {
  constructor() {
    this.trace = []
    this.currentState = {
      x: 0,
      y: 0,
      angle: 0,
      color: '#000000',
      lineWidth: 1,
      isPenDown: true,
      textPrecision: 2,
      textFontSize: 16,
      textAlwaysUp: false,
      textFontFamily: 'Arial'
    }
    this.startTime = Date.now()
  }

  /**
   * 记录一个执行动作
   * @param {string} cmd - 命令类型 (fd, rt, text, o, r, for, if, cin, cout等)
   * @param {Array} args - 命令参数
   * @param {Object} additionalData - 额外数据 (如文本内容、图形参数、控制流信息等)
   */
  record(cmd, args = [], additionalData = {}) {
    const timestamp = Date.now() - this.startTime
    
    const traceEntry = {
      cmd,
      args: [...args],
      timestamp,
      x: this.currentState.x,
      y: this.currentState.y,
      angle: this.currentState.angle,
      color: this.currentState.color,
      lineWidth: this.currentState.lineWidth,
      isPenDown: this.currentState.isPenDown,
      ...additionalData
    }

    this.trace.push(traceEntry)
  }

  /**
   * 更新当前状态
   * @param {Object} newState - 新的状态数据
   */
  updateState(newState) {
    Object.assign(this.currentState, newState)
  }

  /**
   * 获取完整的Trace数据
   * @returns {Array} Trace数据数组
   */
  getTrace() {
    return [...this.trace]
  }

  /**
   * 清空Trace数据
   */
  clear() {
    this.trace = []
    this.startTime = Date.now()
  }

  /**
   * 获取Trace统计信息
   * @returns {Object} 统计信息
   */
  getStats() {
    const stats = {
      totalActions: this.trace.length,
      duration: Date.now() - this.startTime,
      commands: {},
      finalState: { ...this.currentState }
    }

    // 统计各种命令的使用次数
    this.trace.forEach(entry => {
      stats.commands[entry.cmd] = (stats.commands[entry.cmd] || 0) + 1
    })

    return stats
  }

  /**
   * 导出Trace为JSON字符串
   * @returns {string} JSON格式的Trace数据
   */
  exportJSON() {
    return JSON.stringify({
      trace: this.trace,
      stats: this.getStats(),
      metadata: {
        version: '1.0',
        timestamp: new Date().toISOString(),
        language: 'GOC'
      }
    }, null, 2)
  }

  /**
   * 从JSON导入Trace数据
   * @param {string} jsonData - JSON格式的Trace数据
   */
  importJSON(jsonData) {
    try {
      const data = JSON.parse(jsonData)
      this.trace = data.trace || []
      this.startTime = Date.now()
      return true
    } catch (error) {
      logger.error('Failed to import trace data:', error)
      return false
    }
  }

  /**
   * 🔥 新增：记录控制流指令
   * @param {string} type - 控制流类型 (for, if, while等)
   * @param {string} condition - 条件或循环表达式
   * @param {Object} additionalData - 额外数据
   */
  recordControlFlow(type, condition, additionalData = {}) {
    // 🎯 简化cmd名称：直接使用type作为cmd
    this.record(type, [condition], {
      controlType: type,
      condition: condition,
      ...additionalData
    })
  }

  /**
   * 🔥 新增：记录输入输出指令
   * @param {string} type - IO类型 (cin, cout, cinWin等)
   * @param {string} content - 输入输出内容
   * @param {Object} additionalData - 额外数据
   */
  recordIO(type, content, additionalData = {}) {
    // 🎯 简化cmd名称：直接使用type作为cmd
    this.record(type, [content], {
      ioType: type,
      content: content,
      ...additionalData
    })
  }

  /**
   * 🔥 新增：记录系统指令
   * @param {string} type - 系统指令类型 (wait, cls等)
   * @param {Array} args - 指令参数
   * @param {Object} additionalData - 额外数据
   */
  recordSystem(type, args = [], additionalData = {}) {
    this.record(`system_${type}`, args, {
      systemType: type,
      ...additionalData
    })
  }

  /**
   * 🔥 新增：记录声明指令
   * @param {string} declarationType - 声明类型 (array, variable)
   * @param {string} fullDeclaration - 完整声明语句
   * @param {string} dataType - 数据类型
   * @param {string} name - 变量/数组名
   * @param {number|string} size - 数组大小（仅数组有效）
   * @param {Object} additionalData - 额外数据
   */
  recordDeclaration(declarationType, fullDeclaration, dataType, name, size = null, additionalData = {}) {
    // 🎯 简化cmd名称：直接使用declarationType作为cmd
    // 对于数组，args格式为 "name[size]"
    let args = [fullDeclaration]
    if (declarationType === 'array' && size !== null) {
      args = [`${name}[${size}]`]
    }
    
    this.record(declarationType, args, {
      declarationType: declarationType,
      dataType: dataType,
      name: name,
      size: size,
      fullDeclaration: fullDeclaration,
      ...additionalData
    })
  }
}

// 导出TraceCollector类
if (typeof module !== 'undefined' && module.exports) {
  module.exports = TraceCollector
} else if (typeof window !== 'undefined') {
  window.TraceCollector = TraceCollector
}

// ES模块导出
export default TraceCollector
